﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Memo.Electricity.Engine;
using System.Linq;

namespace Memo.Electricity.Game
{
	public class CClockMgr : CBaseOrderBlockMgr
	{
		[SerializeField] private int mInterval;			//移动时间间隔
		[SerializeField] private int mMoveCount;		//移动数目
		[SerializeField] private int mMaxActiveCount;	//最大同时存在的方块数
		[SerializeField] private int mInitActiveCount;	//初始方块数

		private List<CClock> mClocks;
		private Queue<CClock> mClockQueue;

		private void Awake()
		{
			mClocks = transform.GetComponentsInChildren<CClock>(true).ToList();
			mClocks.Sort((CClock a, CClock b) => a.Order - b.Order);
			mClocks.ForEach((CClock c) => c.gameObject.SetActive(false));

			if (mInitActiveCount >= mClocks.Count || mInitActiveCount > mMaxActiveCount)
			{
				Debug.LogError("方块数目设置错误");
				enabled = false;
				return;
			}
		}

		private void OnEnable()
		{
			Init();
		}

		private void Init()
		{
			mClockQueue = new Queue<CClock>();
			mCurrentIndex = -1;
			for (int i = 0; i < mInitActiveCount; i++)
			{
				++mCurrentIndex;
				mClocks[mCurrentIndex].Enabled();
				mClockQueue.Enqueue(mClocks[mCurrentIndex]);
			}

			RegisterTick(
				() =>
				{
					bool canMove = true;

					for(int i = 0, j = mCurrentIndex; i < mMoveCount; i++)
					{
						if (++j == mClocks.Count)
						{
							j = 0;
						}
						Collider2D[] res = Physics2D.OverlapBoxAll(mClocks[j].transform.position, new Vector2(0.9f, 0.9f), 0);
						foreach(var c in res)
						{
							if ((!c.isTrigger || c.CompareTag("Player")) && c.GetComponent<CClock>() == null)
								canMove = false;
						}
					}

					if(canMove)
					{
						for (int i = 0; i < mMoveCount; i++)
						{
							MoveNext();
						}
					}
				},
				mInterval
			);
		}

		private int mCurrentIndex;
		private void MoveNext()
		{
			if (++mCurrentIndex == mClocks.Count)
			{
				mCurrentIndex = 0;
			}

			mClocks[mCurrentIndex].Enabled();
			mClockQueue.Enqueue(mClocks[mCurrentIndex]);
			while (mClockQueue.Count > mMaxActiveCount)
			{
				mClockQueue.Dequeue().Disabled();
			}
		}

		private void CheckNext(IEnumerator<CClock> start, int num)
		{
			IEnumerator<CClock> it = start;
		}
	}
}